package cn.eleven.gui;

import cn.eleven.entity.User;
import cn.eleven.service.UserService;

import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;

/**
 * 主界面，包含顶栏、左侧导航栏和内容区域
 */
public class MainUI extends JFrame {
    private final UserService userService = new UserService(); // 用户服务类
    private int currentUserId; // 当前用户的ID
    private String currentUsername; // 当前用户的用户名
    private JLabel balanceLabel; // 显示余额的标签
    private JPanel contentPanel; // 内容区域
    private CardLayout cardLayout; // 卡片布局

    /**
     * 构造函数，初始化界面
     * @throws SQLException 数据库异常
     */
    public MainUI() throws SQLException {
        showLoginDialog(); // 显示登录对话框
        initializeUI(); // 初始化界面
    }

    /**
     * 显示登录对话框，获取用户ID和用户名
     */
    private void showLoginDialog() {
        // 创建主面板
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); // 设置内边距
        panel.setBackground(new Color(240, 240, 240)); // 设置背景色

        // 创建约束对象
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // 设置组件间距
        gbc.anchor = GridBagConstraints.WEST; // 左对齐

        // 创建标题标签
        JLabel titleLabel = new JLabel("研习空间管理系统");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(0, 150, 136)); // 设置字体颜色
        gbc.gridwidth = 2; // 跨两列
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(titleLabel, gbc);

        // 创建用户名标签
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(usernameLabel, gbc);

        // 创建用户名输入框
        JTextField usernameField = new JTextField(20);
        usernameField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 1;
        panel.add(usernameField, gbc);

        // 创建密码标签
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(passwordLabel, gbc);

        // 创建密码输入框
        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gbc.gridx = 1;
        gbc.gridy = 2;
        panel.add(passwordField, gbc);

        // 创建登录按钮
        JButton loginButton = new JButton("登录");
        loginButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        loginButton.setBackground(new Color(0, 150, 136)); // 设置背景色
        loginButton.setForeground(Color.BLACK); // 设置字体颜色
        loginButton.setFocusPainted(false); // 去除焦点边框
        loginButton.addActionListener(e -> {
            User user = userService.authenticate(
                    usernameField.getText(),
                    new String(passwordField.getPassword())
            );

            if (user != null) {
                currentUserId = user.getId();
                currentUsername = user.getUsername();
                dispose(); // 关闭登录窗口
                try {
                    initializeUI(); // 初始化主界面
                    setVisible(true); // 显示主界面
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(this, "登录失败，请检查用户名和密码！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.anchor = GridBagConstraints.CENTER; // 居中对齐
        panel.add(loginButton, gbc);
// 创建注册按钮
        JButton registerButton = new JButton("注册");
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        registerButton.setBackground(new Color(100, 181, 246)); // 设置背景色
        registerButton.setForeground(Color.BLACK); // 设置字体颜色
        registerButton.setFocusPainted(false); // 去除焦点边框
        registerButton.addActionListener(e -> {
            new RegisterDialogUI(this, userService); // 打开注册窗口
        });

// 调整位置
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        gbc.gridy = 4;
        panel.add(registerButton, gbc);

        // 创建并显示对话框
        JDialog loginDialog = new JDialog(this, "登录", true);
        loginDialog.setContentPane(panel);
        loginDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        loginDialog.pack();
        loginDialog.setLocationRelativeTo(null); // 居中显示
        loginDialog.setVisible(true);
    }

    /**
     * 初始化界面布局和组件
     * @throws SQLException 数据库异常
     */
    private void initializeUI() throws SQLException {
        setTitle("研习空间管理系统"); // 设置窗口标题
        setSize(1024, 768); // 设置窗口大小
        setDefaultCloseOperation(EXIT_ON_CLOSE); // 设置关闭操作

        // 创建顶栏，显示用户名和退出登录按钮
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); // 底部边框黑线

        // 左侧：显示用户名
        JLabel usernameLabel = new JLabel("当前用户: " + currentUsername);
        usernameLabel.setFont(new Font("微软雅黑", Font.BOLD, 14));
        topPanel.add(usernameLabel, BorderLayout.WEST);

        // 获取当前用户信息
        User user = userService.findUserById(currentUserId);
        User.currentBalance = user.getUserBalance(); // 读取数据库余额

        // 创建一个中间面板用于居中对齐
        JPanel centerPanel = new JPanel(new GridBagLayout());
        centerPanel.setOpaque(false); // 透明背景，不影响原布局

        balanceLabel = new JLabel();
        balanceLabel.setText("当前余额：" + User.currentBalance + " 元");
        balanceLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        // 将 balanceLabel 添加到居中面板
        centerPanel.add(balanceLabel);

        topPanel.add(centerPanel, BorderLayout.CENTER); // 放入 topPanel 的 CENTER 区域


        // **添加定时任务，每秒刷新一次余额**
        new Timer(1000, e -> {
            User updatedUser = userService.findUserById(currentUserId);
            User.currentBalance = updatedUser.getUserBalance(); // 更新余额
            balanceLabel.setText("当前余额：" + User.currentBalance + " 元");
        }).start();


        // 右侧：退出登录按钮
        JButton logoutButton = new JButton("退出登录");
        logoutButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        logoutButton.addActionListener(e -> {
            // 退出登录，返回登录页面
            dispose(); // 关闭当前窗口
            try {
                new MainUI().setVisible(true); // 重新显示登录界面
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        });
        topPanel.add(logoutButton, BorderLayout.EAST);

        getContentPane().add(topPanel, BorderLayout.NORTH);

        // 创建左侧导航栏
        JPanel navPanel = new JPanel();
        navPanel.setLayout(new BoxLayout(navPanel, BoxLayout.Y_AXIS));
        navPanel.setPreferredSize(new Dimension(200, getHeight()));
        navPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK)); // 右侧边框黑线

        JButton bookingButton = new JButton("房间预订");
        bookingButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        bookingButton.addActionListener(e -> cardLayout.show(contentPanel, "RoomBookingUI"));

        JButton profileButton = new JButton("个人中心");
        profileButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));


        profileButton.addActionListener(e -> {
            try {
                showProfileUI();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        });

        navPanel.add(bookingButton);
        navPanel.add(profileButton);

        getContentPane().add(navPanel, BorderLayout.WEST);

        // 创建内容区域，使用 CardLayout
        contentPanel = new JPanel();
        cardLayout = new CardLayout();
        contentPanel.setLayout(cardLayout);

        // 添加房间预订界面
        RoomBookingUI roomBookingUI = new RoomBookingUI(currentUserId, currentUsername);
        contentPanel.add(roomBookingUI, "RoomBookingUI");


        // 添加个人中心界面
        ProfileUI profileUI = new ProfileUI(currentUserId);
        contentPanel.add(profileUI, "ProfileUI");

        getContentPane().add(contentPanel, BorderLayout.CENTER);

        // 默认显示房间预订界面
        cardLayout.show(contentPanel, "RoomBookingUI");
    }


    /**
     * 显示个人中心界面
     * @throws SQLException 数据库异常
     */
    private void showProfileUI() throws SQLException {
        ProfileUI profileUI = new ProfileUI(currentUserId);
//        contentPanel.add(profileUI, "ProfileUI");
        cardLayout.show(contentPanel, "ProfileUI");
    }

    /**
     * 主方法，启动应用程序
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // 设置系统默认外观
            } catch (Exception ignored) {}

            try {
                new MainUI().setVisible(true); // 创建并显示主界面
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }
}